'use strict';

const moment = require('moment');
const xmlbuilder = require('xmlbuilder');
const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
    this.ctx.logger.info('ttt...');
    let ua;
    if (this.ctx.headers['user-agent']) {
      ua = this.ctx.headers['user-agent'].toLocaleLowerCase();
      if (ua.includes('iphone') || ua.includes('ipad') || ua.includes('android')) {
        ua = 'mobile';
      } else {
        ua = 'pc';
      }
    } else {
      ua = 'mobile';
    }


    let current_page = parseInt(this.ctx.query.page, 10) || 1;
    current_page = current_page > 0 ? current_page : 1;
    const tab = this.ctx.query.tab || 'yutang';
    const board = this.ctx.query.board || '全部';
    const last = this.ctx.query.last;


    let currentUser = this.ctx.user;


    // 用户没有登录, 直接跳到所有用户展示页
    if (!currentUser && tab == 'attention') {
      return this.ctx.redirect('/user_square');
    }


    let hotsearch;
    // 只有电脑端才需要显示右侧热搜榜
    if (ua == 'pc') {
      hotsearch = await this.service.cacheSvc.get('hotsearch');
    }

    const tabName = this.ctx.helper.tabName(tab);

    let boards = [];

    this.config.tabs.forEach(v => {
      if (v[0] == tab) {
        boards = v[2];
        return;
      }
    });

    let pageTitle;
    if (board && board != '全部') {
      pageTitle = `${board}-${tabName}版块`;
    } else if (tabName) {
      pageTitle = `${tabName}版块`;
    }

    const locals = {
      ua,
      hotsearch,
      tabs: this.config.tabs,
      tab,
      board,
      boards,
      pageTitle,
      order_by: 'last_reply_at',
      user: currentUser,
      has_unread_topic: false,
      customize_records: this.config.customize_records.slice(0, 16),
      url: '/indexScroll',
      params: JSON.stringify({tab, board})
    };


    if (tab == 'attention' && currentUser) {
      // 更新用户的last_click_tab_attention字段
      await this.ctx.model.User.findByIdAndUpdate({_id: currentUser.id}, {
        $set: {last_click_tab_attention: new Date()},
      })


      const followings = await this.ctx.service.attentionSvc.getUnreadFollowingsInfo(currentUser);
      if (!followings || followings.length == 0) {
        return this.ctx.redirect('/user_square');
      }
      let unread_cnt = followings.filter(v => v.unread).length;
      const min_slice_idx = 100;
      const slice_idx = unread_cnt > min_slice_idx ? unread_cnt : min_slice_idx;
      locals.followings = followings.slice(0, slice_idx);
    }

    await this.ctx.renderX('index.nj', locals);
  }


  async indexScroll(ctx) {
    let current_page = parseInt(this.ctx.query.page, 10) || 1;
    current_page = current_page > 0 ? current_page : 1;
    const tab = this.ctx.query.tab || 'yutang';
    const board = this.ctx.query.board || '全部';

    // 获取文章列表的查询条件
    const query = {};

    let currentUser = this.ctx.user;

    if (currentUser) {
      query.author_name = {$nin: currentUser.ignore_users};
    }


    if (tab == 'attention') {
      query.author_name = {$in: currentUser.followings.map(v => v.name)};
    } else {
      if (tab === 'good') {
        query.good = true;
      } else {
        query.tab = tab;
        if (board && board != '全部') {
          query.boards = board;
        }
      }
    }
    if (!query.good) {
      // site页取最近三年的数据
      query.updatedAt = {
        $gte: moment()
          .subtract(3, 'years')
          .toDate(),
      };
    }

    let page_size = this.config.list_topic_count;


    const options = {
      skip: (current_page - 1) * page_size,
      limit: page_size,
      sort: '-top -last_reply_at',
    };

    // 为了避免翻页时产生的数据重复问题
    const last = ctx.query.last;
    if (last) {
      delete options.skip;
      const last_time = new Date(last);
      query.last_reply_at = {'$lt': last_time};
    }

    let topics = await this.service.topicSvc.getTopicsByQuery(query, options);

    for (const topic of topics) {
      if (!topic.pic) {
        topic.pic = topic.author_avatar;
      }
    }



    const html = await Promise.all(topics.map(topic => {
      const ua = ctx.get('user-agent');
      if (ctx.helper.isMobile(ua)) {
        // 如果是移动设备...
        return ctx.renderView('mobile/topic/abstract_mobile.nj', {topic, layout: false});
      } else {
        // 如果不是移动设备...
        return ctx.renderView('pc/topic/abstract_pc.nj', {topic, layout: false});
      }
    }));

    ctx.body = html.join('');

  }


  /**
   * 根据标签展示文章列表
   */
  async listByTags(ctx) {
    const tag = ctx.params.tag;
    ctx.logger.info('listByTags:', tag);
    const current_page = parseInt(ctx.val('page')) || 1;
    const page_size = 30;

    const query = {tags: tag};

    const page_opt = {
      skip: (current_page - 1) * page_size,
      limit: page_size,
      sort: '-top -last_reply_at',
    };


    let result = {
      now_user: this.ctx.user,
      tag,
      current_page,
      order_by: 'last_reply_at',
      pageTitle: tag,
      url: '/listByTagsScroll',
      params: JSON.stringify({tag})
    };


    await ctx.renderX('topic/tag_topics.nj', result);
  }


  /**
   * 根据标签展示文章列表(分页)
   */
  async listByTagsScroll(ctx) {
    const tag = ctx.query.tag;
    const current_page = parseInt(ctx.val('page')) || 1;
    const page_size = this.config.list_topic_count;

    const query = {tags: tag};

    const page_opt = {
      skip: (current_page - 1) * page_size,
      limit: page_size,
      sort: '-top -last_reply_at',
    };

    const topics = await this.service.topicSvc.selectTopics(query, page_opt);

    for (const topic of topics) {
      if (!topic.pic) {
        topic.pic = topic.author_avatar;
      }
    }

    const html = await Promise.all(topics.map(topic => {
      const ua = ctx.get('user-agent');
      if (ctx.helper.isMobile(ua)) {
        // 如果是移动设备...
        return ctx.renderView('mobile/topic/abstract_mobile.nj', {topic, layout: false});
      } else {
        // 如果不是移动设备...
        return ctx.renderView('pc/topic/abstract_pc.nj', {topic, layout: false});
      }
    }));

    ctx.body = html.join('');
  }


  async sitemap() {
    const urlset = xmlbuilder.create('urlset', {
      version: '1.0', encoding: 'UTF-8',
    });
    urlset.att('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');

    let sitemapData = await this.service.cacheSvc.get('sitemap');
    if (!sitemapData) {
      const topics = await this.service.topicSvc.getLimit5w();
      topics.forEach(topic => {
        urlset.ele('url').ele('loc', 'http://taoshajs.org/topic/' + topic._id);
      });
      sitemapData = urlset.end();
      // 缓存一天
      await this.service.cacheSvc.setex('sitemap', sitemapData, 3600 * 24);
    }

    this.ctx.type = 'xml';
    this.ctx.body = sitemapData;
  }

  async appDownload() {
    this.ctx.redirect('https://github.com/soliury/noder-react-native/blob/master/README.md');
  }
}

module.exports = HomeController;
